package com.dny.asmtop;

import com.dny.asmtop.ClassBuilder.ClassKey;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by jlutt on 2018-01-15.
 * 带有缓存的类加载器
 * @author jlutt
 */
public class ASMClassLoader extends ClassLoader {

  private final Map<ClassKey<?>, Class<?>> definedClasses = new HashMap<>();

  private ASMClassLoader() {
  }

  private ASMClassLoader(ClassLoader parent) {
    super(parent);
  }

  public static ASMClassLoader create() {
    return new ASMClassLoader();
  }

  public static ASMClassLoader create(ClassLoader parent) {
    return new ASMClassLoader(parent);
  }

  public Class<?> loadClass(String name, ClassKey<?> key, byte[] b) {
    Class<?> clazz = defineClass(name, b, 0, b.length);
    definedClasses.put(key, clazz);
    return clazz;
  }

  public Class<?> loadClassByKey(ClassKey<?> key) {
    return definedClasses.get(key);
  }

}
